package com.asktgapp.user.fragment;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.asktgapp.JGTool.EmojiFilter;
import com.asktgapp.JGTool.JGColor;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.dialog.ChooseTypeFragment;
import com.asktgapp.dialog.DatePickerFragment;
import com.asktgapp.dialog.JgLowDialog;
import com.asktgapp.model.BrandVO;
import com.asktgapp.model.DeviceTypeVO;
import com.asktgapp.model.LawVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.ChooseBrandActivity;
import com.asktgapp.user.activity.ChooseCityActivity;
import com.bigkoo.pickerview.TimePickerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/30
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class HelpCheckFragment extends BaseFragment {
//    @InjectView(R.id.et_address)
//    EditText mDetailAddress;
    @InjectView(R.id.tv_check_date)
    TextView mCheckDate;
    @InjectView(R.id.tv_machine_type)
    TextView mMachineType;
    @InjectView(R.id.tv_brand)
    TextView mBrand;
    @InjectView(R.id.et_version)
    EditText mVersion;
    @InjectView(R.id.et_weight)
    EditText mWeight;
    @InjectView(R.id.tv_address)
    TextView mMachineAddress;
    @InjectView(R.id.tv_made_date)
    TextView mMadeDate;
    @InjectView(R.id.et_work_hour)
    EditText mWorkHours;
    @InjectView(R.id.et_remark)
    EditText mRemark;
    @InjectView(R.id.et_name)
    EditText mName;
    @InjectView(R.id.et_phone)
    EditText mPhone;
    @InjectView(R.id.et_person_address)
    EditText mPersonAddress;
    @InjectView(R.id.cb_law)
    CheckBox mLawCheckBox;
    @InjectView(R.id.tv_publish)
    TextView mPublish;
    @InjectView(R.id.tv_law_mz)
    TextView mLawMZ;

    private LawVO mMZ;

    public static final int REQUST_CODE_BRAND = 0x001;
    public static final int REQUST_CODE_ADDRESS = 0x002;

    private String mCityId;
    private String mAreaId;
    private String mDate;
    private String mSelectedTypeId;
    private String mSelectedBrandId;
    private List<DeviceTypeVO> mTypeList = new ArrayList<>();
    private List<BrandVO> mBrandList = new ArrayList<>();
    private EmojiFilter inputFilter;
    InputFilter[] inputFilters;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_used_check, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {

        inputFilter=new EmojiFilter();
        inputFilters=new InputFilter[]{inputFilter};
        mWorkHours.setFilters(inputFilters);
        mVersion.setFilters(inputFilters);
        mWeight.setFilters(inputFilters);
        mMachineAddress.setFilters(inputFilters);
        mRemark.setFilters(inputFilters);
        mName.setFilters(inputFilters);
        mPersonAddress.setFilters(inputFilters);
        getBaseActivity().setBackNavigationIcon();
        mMachineType.setOnClickListener(this);
        mBrand.setOnClickListener(this);
        mMachineAddress.setOnClickListener(this);
        mCheckDate.setOnClickListener(this);
        mMadeDate.setOnClickListener(this);
        mPublish.setOnClickListener(this);
        mLawMZ.setOnClickListener(this);


    }

    @Override
    public void loadData() {

        visibleLoading();
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("type", 3);
        final Call<ApiResponseBody<LawVO>> law = apiservice.xieyiInfo(params);

        law.enqueue(new Callback<ApiResponseBody<LawVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<LawVO>> call, Response<ApiResponseBody<LawVO>> response) {
                inVisibleLoading();
                if (response.isSuccessful()) {
                    LawVO bean = response.body().getResult();
                    setUI(bean);
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<LawVO>> call, Throwable t) {
                inVisibleLoading();

            }
        });
        params.put("type", 2);
        final Call<ApiResponseBody<LawVO>> law1 = apiservice.xieyiInfo(params);
        law1.enqueue(new Callback<ApiResponseBody<LawVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<LawVO>> call, Response<ApiResponseBody<LawVO>> response) {
                if (response.isSuccessful()) {
                    mMZ = response.body().getResult();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<LawVO>> call, Throwable t) {

            }
        });

        HashMap pa = new HashMap();
        Call<ApiResponseBody<List<DeviceTypeVO>>> call = apiservice.getTypeList(pa);
        call.enqueue(new Callback<ApiResponseBody<List<DeviceTypeVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Response<ApiResponseBody<List<DeviceTypeVO>>> response) {
                if (response.isSuccessful()) {
                    mTypeList = response.body().getResult();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    private void setUI(LawVO bean) {
        JgLowDialog jgLowDialog = new JgLowDialog("故障检测业务说明", bean.getContent());
        jgLowDialog.show(getFragmentManager(), "JgLowDialog");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {


            case R.id.tv_law_mz:
                JgLowDialog jgLowDialog1 = new JgLowDialog("免责声明", mMZ.getContent());
                jgLowDialog1.show(getFragmentManager(), "JgLowDialog1");
                break;
            case R.id.tv_brand:
                if (Util.isEmpty(mSelectedTypeId)) {
                    showTost("请先选择设备类型", 1);
                    return;
                }
                Intent intent = new Intent(getActivity(), ChooseBrandActivity.class);
                intent.putExtra("typeId", mSelectedTypeId);
                startActivityForResult(intent, REQUST_CODE_BRAND);
                break;
            case R.id.tv_address:
                Intent address = new Intent(getActivity(), ChooseCityActivity.class);
                startActivityForResult(address, REQUST_CODE_ADDRESS);
                break;
            case R.id.tv_machine_type:
                ChooseTypeFragment chooseTypeFragment = new ChooseTypeFragment(new ChooseTypeFragment.Callback() {
                    @Override
                    public void onSelect(String... s) {
                        mMachineType.setText(s[1]);
                        mSelectedTypeId = s[0];
                    }
                }, mTypeList, "请选择设备类型");
                chooseTypeFragment.show(getFragmentManager(), "ChooseTypeFragment");
                break;
            case R.id.tv_check_date:
//                DatePickerFragment picker = new DatePickerFragment(new DatePickerDialog.OnDateSetListener() {
//                    @Override
//                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//
//                        mDate = Utils.getDateString(year, month, dayOfMonth);
//                        if (!Utils.isFutureDate(mDate)) {
//                            showTost("不能选择过去的时间！", 1);
//                        } else
//                            mCheckDate.setText(mDate);
//                    }
//                });
//                picker.show(getFragmentManager(), "DatePickerFragment");
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date2, View v) {//选中事件回调
                        if (!Utils.isFutureDate(Util.DateToStr(date2, "yyyy-MM-dd"))) {
                            showTost("不能选择过去的时间！", 1);
                        } else
                            mCheckDate.setText(Util.DateToStr(date2, "yyyy-MM-dd"));

                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setContentSize(20)//滚轮文字大小
                        .setTitleSize(20)//标题文字大小
//                        .setTitleText("请选择时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                        .setTitleColor(Color.BLACK)//标题文字颜色
                        .setSubmitColor(JGColor.APP_BASIC_BLUE)//确定按钮文字颜色
                        .setCancelColor(JGColor.APP_BASIC_BLUE)//取消按钮文字颜色
//                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
//                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
//                        .setLabel("年","月","日","时","分","秒")
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .isDialog(true)//是否显示为对话框样式
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;
            case R.id.tv_made_date:
//                DatePickerFragment picker1 = new DatePickerFragment(new DatePickerDialog.OnDateSetListener() {
//                    @Override
//                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//
//                        mDate = Utils.getDateString(year, month, dayOfMonth);
//                        if (!Utils.isGoneDate(mDate)) {
//                            showTost("不能选择将来的时间！", 1);
//                        } else
//                            mMadeDate.setText(mDate);
//                    }
//                });
//                picker1.show(getFragmentManager(), "DatePickerFragmen");
                TimePickerView pvTime1 = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date2, View v) {//选中事件回调
                        if (!Utils.isGoneDate(Util.DateToStr(date2, "yyyy-MM-dd"))) {
                            showTost("不能选择将来的时间！", 1);
                        } else
                            mMadeDate.setText(Util.DateToStr(date2, "yyyy-MM-dd"));

                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setContentSize(20)//滚轮文字大小
                        .setTitleSize(20)//标题文字大小
//                        .setTitleText("请选择时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                        .setTitleColor(Color.BLACK)//标题文字颜色
                        .setSubmitColor(JGColor.APP_BASIC_BLUE)//确定按钮文字颜色
                        .setCancelColor(JGColor.APP_BASIC_BLUE)//取消按钮文字颜色
//                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
//                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
//                        .setLabel("年","月","日","时","分","秒")
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .isDialog(true)//是否显示为对话框样式
                        .build();
                pvTime1.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime1.show();
                break;
            case R.id.tv_publish:
                doPublish();
                break;
        }
    }

    private void doPublish() {

        hideSoftKeyboard();
//        if (Util.isEmpty(mDetailAddress.getText().toString().trim())) {
//            showTost("请输入详细地址", 1);
//            return;
//        }
        if (Util.isEmpty(mCheckDate.getText().toString())) {
            showTost("请选择检测日期", 1);
            return;
        }
        if (Util.isEmpty(mSelectedTypeId) || Util.isEmpty(mMachineType.getText().toString().trim())) {
            showTost("请选择机械类型", 1);
            return;
        }
        if (Util.isEmpty(mSelectedBrandId) || Util.isEmpty(mBrand.getText().toString().trim())) {
            showTost("请选择品牌", 1);
            return;
        }
        if (Util.isEmpty(mVersion.getText().toString())) {
            showTost("请输入型号", 1);
            return;
        }
        if (mVersion.getText().toString().length() > 20) {
            showTost("型号长度不能超过20字,当前字数" + mVersion.getText().toString().length(), 1);
            return;
        }
        if (Util.isEmpty(mWeight.getText().toString())) {
            showTost("请输入吨位", 1);
            return;
        }

        if (Util.isEmpty(mMachineAddress.getText().toString()) || Util.isEmpty(mAreaId)) {
            showTost("请选择设备所在地", 1);
            return;
        }
        if (Util.isEmpty(mMadeDate.getText().toString())) {
            showTost("请选择出厂日期", 1);
            return;
        }
        if (Util.isEmpty(mWorkHours.getText().toString())) {
            showTost("请选择设备状态", 1);
            return;
        }
        if (Util.isEmpty(mRemark.getText().toString()) || mRemark.getText().toString().length() < 10) {
            showTost("请输入补充说明（最少十个字）", 1);
            return;
        }
        if (mRemark.getText().toString().length() > 200) {
            showTost("补充说明字数不能超过200字，当前字数：" + mRemark.getText().toString().length(), 1);
            return;
        }
        if (Util.isEmpty(mName.getText().toString())) {
            showTost("请输入联系人姓名", 1);
            return;
        }
        if (Util.isEmpty(mPhone.getText().toString())) {
            showTost("请输入联系电话", 1);
            return;
        }
        if (!Util.isMobileNO(mPhone.getText().toString())) {
            showTost("请输入正确的手机号码", 1);
            return;
        }
        if (Util.isEmpty(mPersonAddress.getText().toString())) {
            showTost("请填写联系人地址", 1);
            return;
        }
        if (!mLawCheckBox.isChecked()) {
            showTost("您未勾选《免责声明》，如果您同意该协议，请勾选", 1);
            return;
        }

        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
//        params.put("equipAddress", mDetailAddress.getText().toString().trim());
        params.put("detectionDate", mCheckDate.getText().toString());
        params.put("typeId", mSelectedTypeId);
        params.put("brandId", mSelectedBrandId);
        params.put("model", mVersion.getText().toString());
        params.put("tonnage", mWeight.getText().toString());
        params.put("productionDate", mMadeDate.getText().toString());
        params.put("workingHours", mWorkHours.getText().toString());
        params.put("info", mRemark.getText().toString());
        params.put("linkName", mName.getText().toString());
        params.put("linkPhone", mPhone.getText().toString());
        params.put("linkAddress", mPersonAddress.getText().toString());
        params.put("city_id", mCityId);
        params.put("area_id", mAreaId);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.subGZCheck(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    showTost("发布成功", 1);
                    getActivity().finish();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });


    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUST_CODE_BRAND) {
                mBrand.setText(data.getStringExtra("brand"));
                mSelectedBrandId = data.getStringExtra("brandId");
            }
            if (requestCode == REQUST_CODE_ADDRESS) {
                mAreaId = data.getStringExtra("areaId");
                mCityId = data.getStringExtra("cityId");
                mMachineAddress.setText(data.getStringExtra("area") + "  " + data.getStringExtra("city"));
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
